<?php

class Database extends Core {
	protected $connection = null;
	protected $connected = false;
	protected $resource;
	public $queries = array();
	
	public function __construct() {
		$this->connect();
	}
	
	public function connect() {
		$config = $this->Config->db;
		$os = $_ENV['OS'];
		if (!empty($os) && strpos($os, 'Windows') !== false) {
			$sep = ',';
		} else {
			$sep = ':';
		}
		$this->connected = false;
		if (is_numeric($config['port'])) {
			$port = $sep . $config['port'];
		} elseif ($config['port'] === null) {
			$port = '';
		} else {
			$port = '\\' . $config['port'];
		}
		$this->connection = mssql_connect($config['host'] . $port, $config['username'], $config['password'], true);
		if (mssql_select_db($config['database'], $this->connection)) {
			$this->connected = true;
		}
		return $this->connected;
	}
	
	public function is_connected() {
		return $this->connected;
	}
	
	public function enabled() {
		return extension_loaded('mssql');
	}
	
	protected function escape($data) {
	    if ($data === null) {
        	return 'NULL';
        } elseif (is_integer($data)) {
        	return $data;
        } elseif (is_bool($data)) {
        	return $data ? 1 : 0;
        }		
        $non_displayables = array(
            '/%0[0-8bcef]/',
            '/%1[0-9a-f]/',
            '/[\x00-\x08]/',
            '/\x0b/',
            '/\x0c/',
            '/[\x0e-\x1f]/'
        );
        foreach ($non_displayables as $regex) {
            $data = preg_replace($regex, '', $data);
        }
        $data = str_replace("'", "''", $data);
        return "'" . $data . "'";
    }
	
    public function query($string, $params = null) {
        if (!is_array($params)) {
            $params = func_get_args();
            $params = array_slice($params, 1);
        }
        if (count($params)) {
            foreach ($params as $key => $value) {
                $params[$key] = $this->escape($value);
            }
            $string = vsprintf($string, $params);
        }
        $timing = microtime(true);
        $this->resource = mssql_query($string, $this->connection);
		$timing = (int)((microtime(true) - $timing) * 1000);
        $this->queries[] = array($timing, $string);
        return $this;
    }
    
	public function fetch($type = 'assoc') {
		$type = 'mssql_fetch_' . $type;
		$result = $type($this->resource);
		return $result;
	}
	
	public function fetch_all($type = 'assoc') {
		$type = 'mssql_fetch_' . $type;
		$result = array();
		while ($row = $type($this->resource)) {
			$result[] = $row;
		}
		return $result;
	}
	
	public function last_insert_id() {
		$id = $this->query('SELECT SCOPE_IDENTITY() AS insert_id')->fetch();
		return $id['insert_id'];
	}
	
	public function num_rows() {
		return mssql_num_rows($this->resource);
	}
}

?>